import ast
import codecs

class Cache:
    cache_file_name = str()
    cache_file_obj = None
    cache_items = dict()
    
    def load_cache(self):
        try:
            self.cache_file_obj = codecs.open(self.cache_file_name, "r+", 
                                              encoding="utf-8")

        except IOError as strerror:
            print strerror
            print IOError.message
            raise IOError
        
        all_places = self.cache_file_obj.readlines()
        
        if all_places:
            self.cache_items = ast.literal_eval(*all_places)
        
    def write_cache_to_disk(self):
        if self.cache_file_obj:
            try:
                self.cache_file_obj.seek(0)
                self.cache_file_obj.write(str(self.cache_items))
                self.cache_file_obj.truncate()
                self.cache_file_obj.close()
                
            except IOError:
                raise IOError


    def add_items(self, new_items):
        if new_items:
            self.cache_items.update(new_items)
        
        return True
    
    def get_item(self, key):
        try:
            item = self.cache_items[key]
            return item 
        
        except KeyError:
            return {}
    
    def dump_cache_contents(self):
        self.load_cache()
        
        for key, value in self.cache_items.iteritems():
            print "{0}|{1}, {2}".format(key, value['lat'], value['lng'])

    def __init__(self, file_name):
        self.cache_file_name = file_name
        self.cache_items = {}
        
